package com.ccys.cms.service.corporateAndInsurance.impl;

import cn.hutool.core.util.ObjectUtil;
import com.ccys.cms.service.corporateAndInsurance.GroupingPolicyService;
import com.ccys.cms.service.corporateAndInsurance.GroupingService;
import com.ccys.common.util.Kit;
import com.ccys.common.vo.ResponseResult;
import com.ccys.db.dto.corporateAndInsurance.GroupingDto;
import com.ccys.db.entity.TblGrouping;
import com.ccys.db.entity.TblGroupingPolicy;
import com.ccys.db.mapper.TblGroupingMapper;
import com.ccys.db.mapper.TblGroupingPolicyMapper;
import com.ccys.db.page.PageDto;
import com.ccys.db.rely.service.impl.BaseServiceImpl;
import com.ccys.db.service.BaseTblAuditTrailWebService;
import com.ccys.db.vo.corporateAndInsurance.GroupingPageQueryVo;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @program: WhiteCoat
 * @description: 分组接口实现类
 * @author: ZhangJingCan
 * @create: 2023-12-20 16:49
 **/

@Service
public class GroupingServiceImpl extends BaseServiceImpl<TblGrouping> implements GroupingService {

    /**
     * 分组
     */
    @Resource
    private TblGroupingMapper tblGroupingMapper;

    /**
     * 分组副表 - 关联表
     */
    @Resource
    private TblGroupingPolicyMapper tblGroupingPolicyMapper;

    @Autowired(required = false)
    private GroupingPolicyService groupingPolicyService;

    @Autowired(required = false)
    private BaseTblAuditTrailWebService baseTblAuditTrailWebService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult saveGrouping(GroupingDto dto) throws ParseException {
        //校验字段
        Kit.allParamValid(dto, "type", "countryId", "name", "status", "startDate", "allowedRecurringAppointment"
                , "allowedMedicationRefill", "allowedServiceReminder");
        //如果type不为0 - 需要校验policyIds是否有值
        if (dto.getType() != 0) {
            if (ObjectUtil.isEmpty(dto.getPolicyIds())) {
                return ResponseResult.error("Parameter abnormality!");
            }
        }

        //检查是否有重复数据
        Example example = new Example(TblGrouping.class);
        example.createCriteria()
                .andEqualTo("countryId", dto.getCountryId())
                .andEqualTo("type", dto.getType())
                .andEqualTo("name", dto.getName())
                .andEqualTo("delFlag", 0);
        //判断是否为修改 - 如果为修改需要排除自身
        if (ObjectUtil.isNotEmpty(dto.getId())) {
            example.createCriteria().andNotEqualTo("id", dto.getId());
        }
        //查询并判断 - 存在则返回错误信息
        if (ObjectUtil.isNotEmpty(tblGroupingMapper.selectOneByExample(example))) {
            return ResponseResult.error("The current country's type already has this name");
        }
        //返回的信息
        String message = "";

        //以上校验都通过 - 开始新增或修改
        if (ObjectUtil.isEmpty(dto.getId())) {
            //新增
            tblGroupingMapper.insertSelective(dto);
            message = "Added successfully";
        } else {
            //修改
            tblGroupingMapper.updateByPrimaryKeySelective(dto);
            //修改需要删除副表
            Example groupingPolicyExample = new Example(TblGroupingPolicy.class);
            groupingPolicyExample.createCriteria().andEqualTo("groupingId", dto.getId());
            tblGroupingPolicyMapper.deleteByExample(groupingPolicyExample);
            message = "Modified successfully";
        }

        //新增副表数据
        if (ObjectUtil.isNotEmpty(dto.getPolicyIds())) {
            List<TblGroupingPolicy> tblGroupingPolicyList = new ArrayList<>();
            for (String s : dto.getPolicyIds().split(",")) {
                TblGroupingPolicy tblGroupingPolicy = new TblGroupingPolicy();
                tblGroupingPolicy.setGroupingId(dto.getId());
                tblGroupingPolicy.setPolicyId(s);
                tblGroupingPolicy.setPolicyType(dto.getType());
                tblGroupingPolicy.preInsert();
                tblGroupingPolicyList.add(tblGroupingPolicy);
            }
            groupingPolicyService.insertAll(tblGroupingPolicyList);
        }

        return ResponseResult.success(message);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult deleteGrouping(GroupingDto dto) {
        //判断
        if (ObjectUtil.isEmpty(dto.getId())) {
            return ResponseResult.error("Parameter Error!");
        }
        //准备实体类并赋值
        TblGrouping tblGrouping = new TblGrouping();
        tblGrouping.setId(dto.getId());
        tblGrouping.setDelFlag(1);
        //判断是否修改成功 - 返回不同状态
        if (tblGroupingMapper.updateByPrimaryKeySelective(tblGrouping) > 0) {
            return ResponseResult.success("Delete Successful!");
        }
        return ResponseResult.error("Delete Failed!");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateGroupingStatus(GroupingDto dto) {
        //校验
        if (ObjectUtil.isEmpty(dto.getId()) || ObjectUtil.isEmpty(dto.getStatus())) {
            return ResponseResult.error("Parameter Error!");
        }
        //准备数据修改
        TblGrouping tblGrouping = new TblGrouping();
        tblGrouping.setId(dto.getId());
        tblGrouping.setStatus(dto.getStatus());
        if (tblGroupingMapper.updateByPrimaryKeySelective(tblGrouping) > 0) {
            //保存状态修改日志
            baseTblAuditTrailWebService.saveStatusLog(dto, dto.getStatus());
            return ResponseResult.success("Modified successfully!");
        }
        return ResponseResult.error("Modification failed!");
    }

    @Override
    public ResponseResult<PageInfo<GroupingPageQueryVo>, Object> findPageGrouping(GroupingDto dto) {
        dto.setStatus(Optional.ofNullable(dto.getStatus()).filter(s -> s > -1 && s < 2).orElse(null));
        //开启分页
        PageDto.startPage();
        List<GroupingPageQueryVo> list = tblGroupingMapper.findPageGrouping(dto);
        PageInfo<GroupingPageQueryVo> info = new PageInfo<>(list);
        return ResponseResult.success(info);
    }
}
